const { appId, mchId, notifyUrl, key, url } = require('../config')
const { genRandomStr, xml2js, js2xml } = require('../utils/tool')
const qs = require('querystring')
const crypto = require('crypto')
const { post } = require('../model/http')
const qrcode = require('qrcode')

const genSign = (params) => {

  //字典序排序
  var newObj = Object.keys(params).sort().reduce((obj, key) => {
    obj[key] = params[key]
    return obj;
  }, {})
  console.log('newObj:', newObj)

  //拼接成字符串stringA
  let stringA = qs.stringify(newObj, null, null, {
    encodeURIComponent: (val) => {
      return qs.unescape(val);
    }
  });
  console.log('stringA:', stringA)

  //拼接上key得到stringSignTemp字符串
  let stringSignTemp = stringA + '&key=' + key;
  console.log('stringSignTemp:', stringSignTemp)

  //对stringSignTemp进行MD5运算，再将得到的字符串所有字符转换为大写，得到sign值signValue

  let sign = crypto.createHash('md5').update(stringSignTemp).digest('hex').toUpperCase();
  console.log('sign:', sign)


  return sign;

}

class Payment {

  //获取二维码
  async getQRcode(ctx) {
    ctx.body = "code"
    //公众账号ID
    let appid = appId;
    //商户号
    let mch_id = mchId;
    //随机字符串
    let nonce_str = genRandomStr(32);

    //商品描述	
    let body = '一瓶可乐';
    //商户订单号	
    let out_trade_no = '20200715002'
    //标价金额	
    let total_fee = 1;

    //终端IP	
    let spbill_create_ip = '127.0.0.1'
    //通知地址	
    let notify_url = notifyUrl
    //交易类型	
    let trade_type = 'NATIVE'


    //数据为集合M
    let params = {
      appid,
      mch_id,
      nonce_str,
      body,
      out_trade_no,
      total_fee,
      spbill_create_ip,
      notify_url,
      trade_type
    }
    //签名	
    let sign = genSign(params);

    let json = {
      xml: {
        ...params,
        sign
      }
    }
    let xml = js2xml(json);
    console.log('xml:', xml)

    let rs = await post(url, xml)
    //将xml转换成js对象，方便取值
    let obj = xml2js(rs.data)
    console.log(obj)

    let imgSource =await qrcode.toDataURL(obj.code_url)
    console.log(imgSource)
    // ctx.body = obj;x
    await ctx.render('index',{code:imgSource})
  }

  notify(ctx){
    console.log('notify:','收到支付结果的通知了。。')
    ctx.body='收到支付结果的通知了'
  }
}

module.exports = new Payment();